<template>
  <view class="page">
    <uni-nav-bar
      :fixed="true"
      :statusBar="true"
      left-icon="left"
      :title="
        isViewMode ? '查看商品' : type === 'add' ? '添加商品' : '编辑商品'
      "
      @clickLeft="handleBack"
    />
    <view class="container">
      <view class="ui-all">
        <view class="uifrom">
          <view>商品分类</view>
          <uni-data-select
            class="uifrom-select"
            placeholder="请选择商品分类"
            v-model="form.commodityClassifyLevel1"
            :localdata="classList"
            :disabled="isViewMode"
            @change="change"
          ></uni-data-select>
        </view>
        <view class="uifrom">
          <view>商品名称</view>
          <input
            type="text"
            placeholder="商品名称必填"
            v-model="form.name"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>规格</view>
          <input
            type="text"
            placeholder="输入规格（以 / 分割）"
            v-model="form.standard"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>尺码</view>
          <input
            type="text"
            placeholder="输入尺码（以 / 分割）"
            v-model="form.sizes"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>型号</view>
          <input
            type="text"
            placeholder="输入型号（以 / 分割）"
            v-model="form.model"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>单价</view>
          <input
            type="number"
            placeholder="输入单价"
            v-model="form.money"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>市场价</view>
          <input
            type="number"
            placeholder="输入市场价"
            v-model="form.marketMoney"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>库存</view>
          <input
            type="number"
            placeholder="输入库存"
            v-model="form.stock"
            :disabled="isViewMode"
          />
        </view>
        <view class="uifrom">
          <view>让利比率</view>
          <uni-data-select
            class="uifrom-select"
            placeholder="请选择让利比率"
            v-model="form.offerDiscountsRatio"
            :localdata="discountRatioList"
            :disabled="isViewMode"
          />
        </view>
      </view>
      <view class="pic-box">
        <view class="ui-all-title">{{
          isViewMode ? "查看商品图片" : "填写商品信息"
        }}</view>

        <!-- 商品展示图 -->
        <view class="upload-section">
          <view class="uifrom">商品展示图</view>
          <UploadMedia
            v-if="!isViewMode"
            v-model="showPicList"
            :max-count="1"
            :max-size="5"
            upload-text="上传展示图"
            upload-type="image"
            @change="handleShowPicChange"
          />
          <view v-else class="view-mode-images">
            <image
              v-if="form.showPic"
              :src="formatImageUrl(form.showPic)"
              mode="aspectFill"
              class="view-image"
            />
          </view>
        </view>

        <!-- 商品轮播图 -->
        <view class="upload-section">
          <view class="uifrom">商品轮播图</view>
          <UploadMedia
            v-if="!isViewMode"
            v-model="carouselList"
            :max-count="3"
            :max-size="5"
            upload-text="上传轮播图"
            upload-type="image"
            tip-text="最多上传3张图片"
            :enable-drag="true"
            @change="handleCarouselChange"
          />
          <view v-else class="view-mode-images">
            <image
              v-if="form.showDetails1"
              :src="formatImageUrl(form.showDetails1)"
              mode="aspectFill"
              class="view-image"
            />
            <image
              v-if="form.showDetails2"
              :src="formatImageUrl(form.showDetails2)"
              mode="aspectFill"
              class="view-image"
            />
            <image
              v-if="form.showDetails3"
              :src="formatImageUrl(form.showDetails3)"
              mode="aspectFill"
              class="view-image"
            />
          </view>
        </view>

        <!-- 商品详情 -->
        <view class="uifrom" v-if="!isViewMode">
          <view>商品详情</view>
          <view class="edit-btn" @click="navTo()">编辑</view>
        </view>
        <view class="detail-preview" v-if="form.contextDetails">
          <view class="preview-title">商品详情预览</view>
          <mp-html :content="form.contextDetails" />
        </view>
      </view>
      <view class="uifrom-save" v-if="!isViewMode">
        <button class="save" @tap="saveInfo()">
          {{ type === "add" ? "确 认 添 加" : "确 认 修 改" }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { formatImageUrl } from "@/utils/filters";
import { useEditorStore } from "@/store/modules/editor";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import { post } from "@/utils/request";
import { getGoodsList, updateGoods, addGoods } from "@/api/goods";
import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
import UploadMedia from "@/components/UploadMedia/UploadMedia.vue";
import rsa from "@/utils/rsa";

// 直接按需调用 rsa

// 使用 store
const editorStore = useEditorStore();
const userStore = useUserStore();
const storeStore = useStoreStore();

// 表单数据
const form = ref({
  // 基本
  id: 0,
  userId: null,
  merchantId: null,
  name: null,
  product: null,
  supplier: null,
  // 分类
  commodityClassifyLevel1: null,
  commodityClassifyLevel2: null,
  // 规格/型号/尺码
  standard: null,
  model: null,
  sizes: null,
  // 价格/库存/销量
  money: null,
  marketMoney: null,
  stock: null,
  sales: null,
  // 图片/链接
  showPic: null,
  showDetails1: null,
  showDetails2: null,
  showDetails3: null,
  link1: null,
  link2: null,
  link3: null,
  // 文本
  contextDetails: null,
  explains: null,
  // 让利比率
  offerDiscountsRatio: null,
});

// 商品分类列表
const classList = ref([]);

// 让利比率列表（3%-20%）
const discountRatioList = ref([]);

// 初始化让利比率列表
const initDiscountRatioList = () => {
  const list = [];
  for (let i = 3; i <= 20; i++) {
    list.push({
      value: i,
      text: `${i}%`,
    });
  }
  discountRatioList.value = list;
};

// 图片列表（用于 UploadMedia 组件）
const showPicList = ref([]);
const carouselList = ref([]);

// 页面类型和商品 ID
const type = ref(null);
const goodsId = ref(null);
// 是否为查看模式
const isViewMode = ref(false);

// 获取商品分类
const getClass = async () => {
  try {
    const res = await post("/api/cc/ccL", {
      pluralId: 0,
      classifyPid: 0,
    });

    if (res.data) {
      classList.value = res.data.map((item) => ({
        value: item.id,
        text: item.classifyName,
      }));
    }
  } catch (error) {
    console.error("获取商品分类失败:", error);
  }
};

// 获取商品详情
const getData = async () => {
  try {
    const res = await getGoodsList({
      id: goodsId.value,
      userId: userStore.userInfo?.userId,
      merchantId: storeStore.storeId,
      limit: 1,
      offset: 1,
    });

    if (res.data?.rows?.[0]) {
      const goodsData = res.data.rows[0];
      form.value = {
        ...goodsData,
        userId: userStore.userInfo?.userId,
        // 转换让利比率：从小数转为百分比整数（例如 0.03 转为 3）
        offerDiscountsRatio: goodsData.offerDiscountsRatio
          ? Math.round(goodsData.offerDiscountsRatio * 100)
          : null,
      };

      // 初始化图片列表
      initImageLists();
    }
  } catch (error) {
    console.error("获取商品详情失败:", error);
    uni.showToast({
      title: "获取商品详情失败",
      icon: "none",
    });
  }
};

// 初始化图片列表（从 form 数据转换为 UploadMedia 组件需要的格式）
const initImageLists = () => {
  // 展示图片
  if (form.value.showPic) {
    showPicList.value = [
      {
        url: form.value.showPic,
        type: "image",
      },
    ];
  } else {
    showPicList.value = [];
  }

  // 轮播图
  const carousel = [];
  if (form.value.showDetails1) {
    carousel.push({
      url: form.value.showDetails1,
      type: "image",
    });
  }
  if (form.value.showDetails2) {
    carousel.push({
      url: form.value.showDetails2,
      type: "image",
    });
  }
  if (form.value.showDetails3) {
    carousel.push({
      url: form.value.showDetails3,
      type: "image",
    });
  }
  carouselList.value = carousel;
};

// 添加商品
const add = async () => {
  if (editorStore.richText) {
    form.value.contextDetails = editorStore.richText;
  }

  // 转换让利比率：从百分比整数转为小数（例如 3 转为 0.03）
  const submitData = {
    ...form.value,
    offerDiscountsRatio: form.value.offerDiscountsRatio
      ? form.value.offerDiscountsRatio / 100
      : null,
  };

  try {
    const res = await addGoods(submitData);

    uni.showToast({
      title: res.message || "添加成功",
      icon: "none",
    });

    if (res.code === 2000) {
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  } catch (error) {
    console.error("添加商品失败:", error);
  }
};

// 修改商品
const edit = async () => {
  if (editorStore.richText) {
    form.value.contextDetails = editorStore.richText;
  }

  // 兜底 merchantId
  if (!form.value.merchantId) {
    storeStore.hydrateFromStorage();
    form.value.merchantId = Number(storeStore.storeId) || 0;
  }

  // 转换让利比率：从百分比整数转为小数（例如 3 转为 0.03）
  const submitData = {
    ...form.value,
    offerDiscountsRatio: form.value.offerDiscountsRatio
      ? form.value.offerDiscountsRatio / 100
      : null,
  };

  try {
    const res = await updateGoods(submitData);

    uni.showToast({
      title: res.message || "修改成功",
      icon: "none",
    });

    if (res.code === 2000) {
      setTimeout(() => {
        uni.navigateBack();
      }, 1000);
    }
  } catch (error) {
    console.error("修改商品失败:", error);
  }
};

// 保存商品信息
const saveInfo = () => {
  if (type.value === "add") {
    add();
  } else if (type.value === "edit") {
    edit();
  }
};

// 分类选择变化
const change = (e) => {
  form.value.commodityClassifyLevel1 = e;
};

// 展示图片变化
const handleShowPicChange = (fileList) => {
  if (fileList && fileList.length > 0) {
    form.value.showPic = fileList[0].url;
  } else {
    form.value.showPic = null;
  }
};

// 轮播图变化
const handleCarouselChange = (fileList) => {
  form.value.showDetails1 = fileList[0]?.url || null;
  form.value.showDetails2 = fileList[1]?.url || null;
  form.value.showDetails3 = fileList[2]?.url || null;
};

// 跳转到富文本编辑页面
const navTo = () => {
  // 进入编辑器前，把当前详情放入 Pinia，便于编辑页面加载
  if (form.value.contextDetails) {
    editorStore.setRichText(form.value.contextDetails);
  }
  uni.navigateTo({
    url: "./editDetails",
  });
};

// 返回上一页
const handleBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};

// 页面加载
onLoad((option) => {
  // 初始化用户信息
  userStore.hydrateFromStorage();
  storeStore.hydrateFromStorage();
  // 设置表单的 userId
  form.value.userId = userStore.userInfo?.userId;
  form.value.merchantId = Number(storeStore.storeId) || 0;

  getClass();
  // 初始化让利比率列表
  initDiscountRatioList();
  type.value = option.type;
  // 设置查看模式
  isViewMode.value = option.type === "view";
  if (option.goodsId) {
    goodsId.value = option.goodsId;
    getData();
  }
});

// 从编辑器返回后回填最新详情
onShow(() => {
  if (editorStore.richText) {
    form.value.contextDetails = editorStore.richText;
  }
  // 确保 merchantId 随时有值
  if (!form.value.merchantId) {
    storeStore.hydrateFromStorage();
    form.value.merchantId = Number(storeStore.storeId) || 0;
  }
});
</script>

<style lang="scss">
.page {
  width: 100%;
  height: 100vh;
  background-color: #f5f5f5;
}

.container {
  display: block;
  padding-top: 30rpx;
  padding-bottom: 200rpx;
}

.ui-all {
  width: 95vw;
  background-color: #ffffff;
  padding: 10upx 40upx;
  border-radius: 20upx;
  margin: 0 auto;

  .ui-all-title {
    padding-top: 20rpx;
    padding-bottom: 20rpx;
    font-weight: 600;
  }
}

.ui1-box {
  width: 95vw;
  background-color: #ffffff;
  padding: 10upx 40upx;
  border-radius: 20upx;
  margin: 30upx auto 0;
}

.ui-box {
  width: 95vw;
  background-color: #ffffff;
  padding: 10upx 40upx;
  border-radius: 20upx;
  margin: 30upx auto 0;
}

.pic-box {
  width: 95vw;
  background-color: #ffffff;
  padding: 10upx 40upx;
  border-radius: 20upx;
  margin: 30upx auto;

  .upload-section {
    margin-bottom: 30rpx;
  }

  .view-mode-images {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    margin-top: 20rpx;

    .view-image {
      width: 200rpx;
      height: 200rpx;
      border-radius: 12rpx;
      border: 1px solid #e8eaed;
    }
  }
}

.uifrom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20upx 0;
  font-size: 28upx;

  .uifrom-time {
    display: flex;
    align-items: center;
    width: 70%;

    text {
      padding: 0 30rpx;
    }
  }

  input,
  .uifrom-select {
    width: 70%;
    font-size: 28upx;
    flex: none;
  }

  ::v-deep .uni-select {
    border: none;
    padding: 0;
    font-size: 28upx;

    .uni-select__input-placeholder {
      font-size: 28upx;
    }
  }

  .uifrom-btn {
    background: $base-color;
    color: #ffffff;
    font-size: 28rpx;
    border-radius: 5upx;
    padding: 6rpx 28rpx;
  }

  .edit-btn {
    background: $base-color;
    color: #ffffff;
    font-size: 28rpx;
    border-radius: 5upx;
    padding: 6rpx 28rpx;
  }
}

.detail-preview {
  margin-top: 30rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;

  .preview-title {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    color: #333;
  }
}

.uifrom-save {
  width: 100%;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  padding: 30rpx 0;
  box-shadow: 0px -1px 3px 0px #dadada;

  .save {
    background: $base-color;
    color: #ffffff;
    margin-top: 40rpx auto;
    font-size: 28rpx;
    width: 95vw;
    border-radius: 50upx;
  }
}
</style>
